﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Benefit.Models.Sys;
namespace Benefit.Service.Month
{
    /// <summary>
    /// 账户资金变动(对于个人多账号后显示的总计值在while循环后重新写一个对象写入)这个是显示在第一行的总数(u)
    /// </summary>
    public class ServiceAccountMonthChange : Benefit.Interface.Month.IAccountMonthChange
    {
        Benefit.DB.DBManager db = null;
        public ServiceAccountMonthChange(Benefit.DB.DBManager db)
        {
            this.db = db;
        }


        /// <summary>
        /// 删除当月所有记录
        /// </summary>
        /// <param name="tradeHistoryId"></param>
        public void Delete(int month, int year)
        {
            var query = from t in db.AccountMonthChange where t.Month == month && t.Year == year select t;
            foreach (Models.Month.AccountMonthChange c in query)
            {
                db.AccountMonthChange.Remove(c);
            }
            db.SaveChanges();
        }

        /// <summary>
        /// 保存账号月变化情况
        /// </summary>
        /// <param name="tradeHistoryId">插入时间编号</param>
        /// <param name="pdate">插入时间</param>
        public void InitMonthAccountChange(int month, int year)
        {
            var query = db.Accounts.ToList();
            foreach (Models.Sys.Account account in query)
            {
                Models.Month.AccountMonthChange change = new Models.Month.AccountMonthChange();
                change.AccountId = account.Id;
                var _query = from t in db.AccountDayChange where t.TradeHistory.MPdate == month && t.TradeHistory.YPdate == year && t.AccountId == account.Id select t;
                var query2 = from t in db.AccountMonthChange where t.Month == month && t.Year == year && t.AccountId == account.Id select t;
                if (query2.Count() > 0)
                {
                    change = query2.First();
                }
                if (_query.Count() > 0)
                {
                    change.BillCount = _query.Sum(a => a.BillCount);
                    change.DayCount = _query.Sum(a => a.DayCount);
                    change.Free = _query.Sum(a => a.Free);
                    change.LoseCount = _query.Sum(a => a.LoseCount);
                    change.Profit = _query.Sum(a => a.Profit);
                    change.SumLost = _query.Sum(a => a.SumLost);
                    change.SumWin = _query.Sum(a => a.SumWin);
                    change.UsedMargin = _query.Sum(a => a.UsedMargin);
                    change.WinCount = _query.Sum(a => a.WinCount);

                }
                change.Year = year;
                change.Month = month;
                if (query2.Count() == 0)
                {
                    db.AccountMonthChange.Add(change);
                }

            }
            db.SaveChanges();
        }
    }
}